
<template>
  <div class="ticket">
    <div class="ticket-container">
      <div style="flex-shrink: 0">
        <u-swiper :list="bannerList" height="360"></u-swiper>
      </div>
      <div class="day-list">
        <div
            @click="checkDate(item)"
            :class="['day-item', activeDay === item.fullDate ? 'active' : '']" v-for="item in dayList">
          <div class="day">{{ item.week }}</div>
          <div class="date">{{ activeDay === item.fullDate ? item.date : item.day}}</div>
        </div>
        <div class="date-icon" @click="show = true">
          <u-icon name="calendar" size="52" color="#FF770F"></u-icon>
          <u-icon name="arrow-down" size="24" color="#FF770F"></u-icon>
        </div>
      </div>
      <div class="content">
        <div class="title">票务信息</div>
        <div class="ticket-list">
          <div class="ticket-item" v-for="item in ticketList" :key="item.id">
            <div>
              <div class="ticket-title">登船时间：{{ item.start_time }}</div>
              <div class="ticket-time" v-if="item.surplus > 0">余票：{{ item.surplus }}张</div>
              <div class="tag-item"  v-if="item.surplus <= 0">售罄</div>
            </div>
            <div class="ticket-item-right">
              <div class="ticket-price">￥{{ item.price }}起</div>
              <div class="ticket-button" @click="toOrder(item)">订</div>
            </div>
          </div>
        </div>
        <div class="title">产品特色</div>
        <u-parse :html="detail.content"></u-parse>
      </div>

    </div>
    <u-popup closeable v-model="show2" mode="bottom" border-radius="14">
      <div class="popup-box">
        <div class="popup-title">订票信息</div>
        <div class="popup-body">
          <div style="display: flex;justify-content: flex-end">
            <div class="add-icon" @click="addUser">
              添加乘船人
            </div>
          </div>
          <scroll-view scroll-y="true" style="max-height: 800rpx; min-height: 300rpx">
            <div class="user-list">
              <div class="user-item" v-for="(item,index) in userList">
                <div class="userinfo">
                  <div class="username">
                    <div style="width: 120rpx">
                      姓名
                    </div>
                    <input type="text" v-model="item.nickname" placeholder="请输入">
                  </div>
                  <div class="username">
                    <div style="width: 120rpx">
                      手机号
                    </div>
                    <input type="tel" v-model="item.phone" placeholder="请输入">
                  </div>
                </div>
                <div class="del-text" @click="userList.splice(index, 1)">删除</div>
              </div>
            </div>
            <u-empty v-if="userList.length === 0"></u-empty>

          </scroll-view>
        </div>
        <div class="popup-footer">
          <div class="total-price">￥ {{ totalPrice || '----' }}</div>
          <div class="order-button" @click="confirmOrder">确定</div>
        </div>
      </div>
    </u-popup>
    <u-calendar
        btn-type="default"
        :min-date="currentDate" max-date="2099" @change="changeDate1" v-model="show" mode="date" active-color="#fff" active-bg-color="#FF770F"  range-color="#fff" range-bg-color="#FF770F"></u-calendar>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import dayjs from "dayjs";
import ticket from "./ticket.vue";
let weekNameList = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
export default {
  name: "index",
  data() {
    return {
      detail: {},
      dayList: [],
      activeDay: dayjs().format('YYYY-MM-DD'),
      show:false,
      currentDate: dayjs().format('YYYY-MM-DD'),
      isDisabled: false,
      ticketList: [],
      show2: false,
      currentTicket: {},
      userList: []
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    totalPrice() {
      let value =  this.userList.reduce((total, item) => {
        let price = 0
        if (item.is_adult) {
          price = parseFloat(this.currentTicket.price) || 0
        } else {
          price = parseFloat(this.currentTicket.child_price) || 0
        }
        return total + price
      }, 0)
      return value.toFixed(2)
    },
    bannerList() {
      return this.detail.images ? this.detail.images.split(',').map(item => {
        return {
          image: item,
        }
      }) : []
    }
  },
  onLoad({ ticketId }) {
    this.$api.getShipDetail({ id: ticketId }).then(res => {
      this.detail = res
      // 设置标题
      uni.setNavigationBarTitle({
        title: res.title
      })
    })
    this.setDate()
    this.$api.getShipScheduleList({
      ship_id: ticketId,
      start_time: this.activeDay
    }).then(res => {
      this.ticketList = res.map(item => {
        let surplus = item.count - item.orderUserList.length
        surplus = surplus < 0 ? 0 : surplus
        return {
          ...item,
          // 余票
          surplus: surplus,
          start_time: dayjs(item.start_time).format('HH:mm')
        }
      })
    })
  },
  methods: {
    setDate(date = dayjs()) {
      // 计算当日或者传入日期至后一周时间成为列表
      let dayList = []
      let currentDate = date
      for (let i = 0; i < 6; i++) {
        let fullDate = currentDate.format('YYYY-MM-DD')
        dayList.push({
          week: weekNameList[currentDate.day()],
          date: currentDate.format('MM-DD'),
          day: currentDate.date(),
          fullDate
        })
        currentDate = currentDate.add(1, 'day')
      }
      this.dayList = dayList
    },
    checkDate(item) {
      this.activeDay = item.fullDate
      // this.setDate(dayjs(item.fullDate))
    },
    changeDate1(e) {
      console.log(e)
      this.activeDay = e.result
      // 往前推三天
      this.setDate(dayjs(this.activeDay).subtract(2, 'day'))
    },
    toOrder(item) {
      this.currentTicket = item
      this.show2 = true
    },
    addUser() {
      if (this.userList.length >= this.currentTicket.surplus) {
        uni.showToast({
          title: '超出余票数量',
          icon: 'none'
        })
      } else {
        this.userList.push({
          nickname: '',
          phone: '',
          is_adult: 1
        })
      }
    },
    confirmOrder() {
      if (!this.userList.length) {
        uni.showToast({
          title: '请添加乘船人',
          icon: 'none'
        })
      }
      // 校验每个用户信息必须存在，并且手机号合法
      let flag = this.userList.every(item => {
        return item.nickname && item.phone && /^1[3456789]\d{9}$/.test(item.phone)
      })
      if (!flag) {
        uni.showToast({
          title: '请填写正确的乘船人信息',
          icon: 'none'
        })
        return
      }
      // 创建订单
      this.$api.createOrder({
        ship_id: this.currentTicket.ship_id,
        cycle_id: this.currentTicket.id, // 周期
        count: this.userList.length,
        status: 0,
        pay_status: 0,
        pay_way: 'wexin',
        total_price: this.totalPrice,
        discount_amount: 0,
        coupon_id: 0,
        amount: this.totalPrice,
        user_id: this.userInfo.id,
        role: this.userInfo.role,
        user_list: this.userList,
      }).then(res => {
        uni.showToast({
          title: '下单成功',
          icon: 'success'
        })
        this.wxH5Pay(res)
      })

    },
    wxH5Pay(orderRes) {
      const { order_no } = orderRes
      this.$api.paymentH5({
        order_no
      }).then(res => {
        WeixinJSBridge.invoke('getBrandWCPayRequest', {
              appId: res.appid,
              timeStamp: res.timestamp,
              nonceStr: res.nonce_str,
              package: res.package,
              signType: res.signType,
              paySign: res.paySign,
            },
            function(res) {
              console.log('下单成功',res)
              if (res.err_msg == "get_brand_wcpay_request:ok") {
                // 使用以上方式判断前端返回,微信团队郑重提示：
                //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                uni.redirectTo({
                  url: '/pages/pay/success'
                })
              } else {
                uni.reLaunch({
                  url: '/pages/order/index'
                })
              }
            });})
    },
  }
}
</script>

<style lang="scss">
.popup-box {
  padding: 24rpx 0rpx;
  padding-bottom: 0;
  .popup-title {
    font-size: 38rpx;
    text-align: center;
    padding-bottom: 20rpx;
  }
  .popup-body {
    background: #F3F3F3;
    padding: 20rpx;
    .add-icon {
      background-color: rgba(255, 153, 0, 0.29);
      color: #ff9900;
      height: 48rpx;
      line-height: 48rpx;
      border-radius: 24rpx;
      padding: 0 12rpx;
      width: 160rpx;
      font-size: 24rpx;text-align: center;
      box-sizing: border-box;
    }

    .user-list {
      .user-item {
        display: flex;
        align-items: center;
        padding: 0 24rpx;
        background-color: #ffffff;
        margin-top: 24rpx;
        .del-text {
          flex-shrink: 0;
          width: 100rpx;
          color: #fa3534;
          font-size: 32rpx;
        }
        .userinfo {
          flex-grow: 1;
          .username {
            font-size: 28rpx;
            color: #333333;
            display: flex;
            align-items: center;
            padding: 24rpx 0;
            border-bottom: 1px solid #f2f2f2;
          }
          .user-phone {
            font-size: 24rpx;
            color: #666666;
            margin-top: 10rpx;
            display: flex;
            align-items: center;
          }
        }
      }
    }
  }
  .popup-footer {
    padding: 32rpx 20rpx;
    background-color: #ffffff;
    border-top: 1px solid #f2f2f2;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .total-price {
      flex-shrink: 0;
      color: #FF770F;
      font-size: 32rpx;
    }
    .order-button {
      width: 160rpx;
      height: 70rpx;
      border-radius: 8rpx;
      line-height: 70rpx;
      text-align: center;
      color: #ffffff;
      font-size: 32rpx;
      background: #FF770F;
      &.disabled {
        background: #999999;
      }
    }
  }
}
page {
  height: 100%;
  overflow: hidden;
}
.ticket {
  position: relative;
  height: 100%;
  .detail-button {
    height: 40rpx;
    line-height: 32rpx;
    text-align: center;
    padding: 4rpx 20rpx;
    font-size: 24rpx;
    color: #ffffff;
    background: #FF770F;
    border-radius: 40rpx 40rpx 40rpx 40rpx;
  }
  .news-item {
    padding: 20rpx;
    border-radius: 20rpx;
    background-color: #ffffff;
    margin-top: 20rpx;
    display: flex;
    .news-right {
      height: 200rpx;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      flex-grow: 1;
      margin-left: 20rpx;
      padding-right: 12rpx;
      .news-title {
        font-size: 32rpx;
        color: #333333;
        font-weight: bold;
      }
      .news-desc {
        font-size: 24rpx;
        color: #666666;
        margin-top: 10rpx;
      }
      .news-bottom {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 10rpx;
        .news-time {
          font-size: 24rpx;
          color: #999999;
        }
      }
    }
  }
  .custom-nav {
    position: fixed;
    top: 20rpx;
    right: 30rpx;
    z-index: 9;
    height: 55rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #F3F3F3;
  }
    .content {
      .title {
        font-size: 36rpx;
        color: #000000;
        font-weight: bold;
        padding: 24rpx;
        background-color: #ffffff;
      }
      .ticket-list {
        padding: 0 16rpx 16rpx;
        color: #333333;
        margin-top: 20rpx;
        .tag-item {
          width: 80rpx;
          text-align: center;
          padding: 4rpx 8rpx;
          border-radius: 4rpx;
          font-size: 24rpx;
          color: #999999;
          border: 2px solid #F3F3F3;
          background-color: #F3F3F3;
          margin-right: 10rpx;
          margin-bottom: 10rpx;
        }
        .ticket-item {
          display: flex;
          align-items: center;
          justify-content: space-between;
          background-color: #ffffff;
          padding: 24rpx;
          border-radius: 12rpx;
          margin-bottom: 12rpx;
          .ticket-title {
            color: #333333;
          }
          .ticket-time {
            font-size: 24rpx;
            color: #666666;
            margin-top: 10rpx;
          }
          .ticket-item-right {
            flex-shrink: 0;
            margin-left: 20rpx;
            display: flex;
            align-items: flex-end;
            height: 100rpx;
            .ticket-price {
              color: #FF770F;
              font-size: 32rpx;
              font-weight: bold;
            }
            .ticket-button {
              width: 80rpx;
              height: 80rpx;
              line-height: 80rpx;
              text-align: center;
              color: #ffffff;
              background: #FF770F;
              border-radius: 8rpx;
              font-size: 36rpx;
              margin-left: 12rpx;
            }
          }
        }
      }
    }

  .top {
    position: absolute;
    width: 100%;
    left: 0;
    top: 0;
    z-index: 1;
    height: 328rpx;
    background: linear-gradient(0deg, #F3F4F4 0%, #FF9346 27%, #FF770F 43%);
    font-size: 24px;
    color: #ffffff;
    font-weight: bold;
    text-align: center;
    line-height: 140rpx;
  }
  .day-list {
    display: flex;
    align-items: center;
    background-color: #ffffff;
    padding: 32rpx;
    margin-bottom: 20rpx;
    margin-top: 20rpx;
    .date-icon {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
    }
    .day-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      border-radius: 8rpx;
      padding: 6rpx 0;
      .day {
        font-size: 24rpx;
        color: #333333;
      }
      .date {
        font-size: 32rpx;
        color: #000000;
        font-weight: bold;
      }
      &.active {
        background-color: #FF770F;
        .day,
        .date {
          color: #ffffff;
        }
      }
    }

  }
  .ticket-container {
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    width: 100%;
    z-index: 2;
    background: #F3F3F3;
    border-radius: 24rpx 24rpx 0 0;
    .content {
      flex-grow: 1;
      overflow: auto;
    }
    .order-button-box {
      flex-shrink: 0;
      padding: 32rpx 20rpx;
      background-color: #ffffff;
      border-top: 1px solid #f2f2f2;
      .order-button {
        height: 70rpx;
        border-radius: 12rpx;
        width: 100%;
        line-height: 70rpx;
        text-align: center;
        color: #ffffff;
        font-size: 32rpx;
        background: #FF770F;
        &.disabled {
          background: #999999;
        }
      }
    }

  }

}
</style>
